package com.yang.modules.common.config;

import cn.hutool.core.net.NetUtil;
import com.yang.common.core.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Billyang
 * @date 2024/12/27 11:21
 */
@Slf4j
@Configuration
public class SnowflakeIdConfiguration {

    @Value("${server.port}")
    private Integer port;
    @Value("${snowflake.datacenter-id}")
    private Long datacenterId;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty("snowflake.datacenter-id")
    public SnowflakeIdWorker snowflakeIdWorker(){
        String ip = NetUtil.getLocalhostStr();
        // 利用ip+端口保证每个服务的workerId不一致，用于ip一致或者端口一致的不同服务
        long workerId = (NetUtil.ipv4ToLong(ip) + port) % (SnowflakeIdWorker.getMaxDatacenterId() + 1);
        log.info("SnowflakeIdWorker init,ip:{},port:{},datacenterId:{},workerId:{}", ip, port, datacenterId, workerId);
        return new SnowflakeIdWorker(workerId, datacenterId);
    }
}
